package cn.slt.controller;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.support.lob.JtaLobCreatorSynchronization;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mysql.jdbc.interceptors.SessionAssociationInterceptor;

import cn.slt.domian.Category;
import cn.slt.domian.MD_ClassDSID;
import cn.slt.domian.MD_Metadata;
import cn.slt.domian.MD_libraryDSID;
import cn.slt.domian.users;
import cn.slt.service.CategoryService;
import cn.slt.service.MD_MetadataService;
import cn.slt.service.MD_ObjDSIDService;
import cn.slt.service.MD_classDSIDService;
import cn.slt.service.MD_libraryDSIDService;
import cn.slt.service.usersService;
import kjoms.udcs.bean.OrgUnitBean;
import kjoms.udcs.invoke.OpenService;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

@Controller
public class loginController {
	@Autowired
	private usersService service;
	@Autowired
	private MD_MetadataService service2;
	@Autowired
	private MD_libraryDSIDService service3;
	@Autowired
	private MD_classDSIDService service4;
	@Autowired
	private CategoryService cateservice;
	@Autowired
	private MD_classDSIDService classDSIDService;
	@Autowired
	private MD_ObjDSIDService objDSIDService;

	@ResponseBody
	@RequestMapping("login")
	public String login(@RequestParam String username) throws UnsupportedEncodingException {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("app-client.xml");
		OpenService service = (OpenService) applicationContext.getBean("openService");
		username= java.net.URLDecoder.decode(username,"UTF-8"); 
		System.out.println(username);
        //验证并且得到部门名称
		
		List<MD_Metadata> list = service2.getall(username);
		List<MD_libraryDSID> list2 = service3.getall(username);

		// for(MD_Metadata l :list)
		// {
		// System.out.println(l.getBuildUnit());
		// System.out.println(l.getOwner());
		// }
		Category category = new Category();
		Category category2 = null;
		for (MD_Metadata metadata : list) {
			category.setFirCode(metadata.getFirstlev());
			category.setSecCode(metadata.getSecondlev());
			if (metadata.getThirdlev().equals("00")) {
				category.setThiCode("01");
			} else {
				category.setThiCode(metadata.getThirdlev());
			}
			try {
				category2 = cateservice.getone(category);
			} catch (Exception e) {
				// TODO: handle exception
			}
			if(category2!=null){
				metadata.setFirstlev(category2.getFirName());
				metadata.setSecondlev(category2.getSecName());
			}
			else{
				metadata.setFirstlev("分类被删除");
				metadata.setSecondlev("分类被删除");
			}
			
			if (metadata.getThirdlev().equals("00")) {
				metadata.setThirdlev("无法确定");
			} else {
				metadata.setThirdlev(category2.getThiName());
			}

		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("meta", list);
		map.put("lib", list2);

		return JSONArray.toJSONString(map);
	}

	@ResponseBody
	@RequestMapping("metafeedback")
	public String metafeedback(HttpServletRequest request) {

		MD_Metadata metadata = service2.getone(request.getParameter("location"), request.getParameter("owner"));
		return JSONArray.toJSONString(metadata);
	}

	@ResponseBody
	@RequestMapping("deletemeta")
	public String deletemeta(HttpServletRequest request) {
		String words = null;
		String location=request.getParameter("location");
		String owner=request.getParameter("owner");
		Map<String, String>map=new HashMap<String, String>();
		map.put("location", location);
		map.put("dsName", owner);
		Integer libdscode=null;
		try {
			libdscode=service3.getdscode(map);
			for(MD_ClassDSID classDSID: service4.getBySupdscode(libdscode)){
				objDSIDService.deleteObj(classDSID.getDsCode());
				System.out.println("delete classname  "+classDSID.getDsName());
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		try {
			service4.deleteClass(libdscode);
		} catch (Exception e) {
			// TODO: handle exception
		}
		try {
			service3.deleteLib(location, owner);
		} catch (Exception e) {
			// TODO: handle exception
		}
		try {
			service2.deleteMeta(location, owner);
		} catch (Exception e) {
			// TODO: handle exception
		}
		try {
			service.deleteUsers(location, owner);
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		
		System.out.println("delete ok!");
		
			return "1";
	}

	@ResponseBody
	@RequestMapping("check")
	public String check(HttpServletRequest request) {

		// System.out.println(request.getParameter("datasent"));
		users users = new users();
		users.setLocation(request.getParameter("location"));
		users.setUsername(request.getParameter("bumen"));
		users.setOwner(request.getParameter("owner"));
		users = service.getall(users);
		System.out.println("check" + JSONArray.toJSONString(users));
		return JSONArray.toJSONString(users);
	}

	@ResponseBody
	@RequestMapping("state1")
	public String state1(HttpServletRequest request) {
		System.out.println("set state1 : " + service.updatestate1(request.getParameter("datasent")));
		// System.out.println("set state1"+service.updatestate1("办公室"));
		return "1";
	}

	@ResponseBody
	@RequestMapping("state0")
	public String state0(HttpServletRequest request) {
		// service.updatestate0("办公室");
		users user = new users();
		user.setLocation(request.getParameter("location"));
		user.setOwner(request.getParameter("owner"));
		user.setUsername(request.getParameter("bumen"));
		System.out.println("set state0 " + service.updatestate0(user));
		return null;
	}

	@ResponseBody
	@RequestMapping("updateusersAndfeedback")
	public String updateusersAndfeedback(HttpServletRequest request) {
		String url = "jdbc:oracle:thin:@";
		users user = new users();
		user.setLocation(request.getParameter("location"));
		user.setOwner(request.getParameter("owner").toUpperCase());
		user.setUsername(request.getParameter("bumen"));
		// System.out.println(request.getParameter("owner"));
		// System.out.println(request.getParameter("bumen"));
		// System.out.println(request.getParameter("location"));
		// service.updateusers(user);
		// System.out.println("update users ? "+service.updateusers(user));

		Map<String, String> map = new HashMap<String, String>();
		System.out.println("userowner" + user.getOwner() + "loc" + user.getLocation());

		map.put("dsName", user.getOwner());
		map.put("location", user.getLocation());

		System.out.println("temp " + JSONArray.toJSONString(service3.gettemp(map)));

		return JSONArray.toJSONString(service3.gettemp(map));
	}

	@ResponseBody
	@RequestMapping("updateusers")
	public String updateusers(HttpServletRequest request) {
		String url = "jdbc:oracle:thin:@";
		users user = new users();
		user.setState("1");
		user.setLocation(request.getParameter("location"));
		user.setOwner(request.getParameter("owner").toUpperCase());
		user.setUsername(request.getParameter("bumen"));
		// System.out.println(request.getParameter("owner"));
		// System.out.println(request.getParameter("bumen"));
		// System.out.println("updateusers _location " +
		// request.getParameter("location"));
		// service.updateusers(user);
		System.out.println("update users ? " + service.updateusers(user));

		// Map<String, String> map=new HashMap<String, String>();
		// map.put("dsName","SLMETADATA" );
		// map.put("location","jdbc:oracle:thin:@121.248.200.5:1521:orcl" );
		//
		// System.out.println("temp"+JSONArray.toJSONString(service3.gettemp(map)));

		return null;
	}

	@ResponseBody
	@RequestMapping("showtables")
	public String showtables(HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("dsName", request.getParameter("owner").toUpperCase());
		map.put("location", request.getParameter("location"));

		MD_Metadata metadata = service2.getone(request.getParameter("location"),
				request.getParameter("owner").toUpperCase());
		if (!metadata.getThirdlev().equals("00"))
			return "0";// 之前指定三级分类则现在不操作
		System.out.println("一级二级编码  " + metadata.getFirstlev() + "  " + metadata.getSecondlev());
		List<Category> categories = cateservice.queryCategoryList(metadata.getFirstlev(), metadata.getSecondlev());
		System.out.println("三级分类个数   " + categories.size());

		service3.getdscode(map); // lib dscode
		System.out.println("dscode   " + service3.getdscode(map));

		List<MD_ClassDSID> classDSIDs = service4.getallbysupdscodeandlevel(service3.getdscode(map));
		if (classDSIDs.size() == 0)
			return "0"; // 无需更新
		System.out.println("符合条件的表      " + classDSIDs.size());

		Map<String, Object> res = new HashMap<String, Object>();
		res.put("dsids", classDSIDs);
		res.put("categories", categories);
		return JSONObject.toJSONString(res);
	}

	@ResponseBody
	@RequestMapping("tablesplit")
	public String tablesplit(HttpServletRequest request) {

		int i = 0;
		JSONArray list = JSONArray.parseArray(request.getParameter("arr"));
		for (Object li : list)

		{

			JSONObject object = JSONObject.parseObject(li.toString());
			String ids = (String) object.get("id");
			String value = (String) object.get("value");
			ids = ids.substring(6);
			int id;
			id = Integer.valueOf(ids);
			try {

				classDSIDService.updateLevelCode(id, value);
			} catch (Exception e) {

				System.out.println("失败 " + i++);
			}

		}

		return "1";
	}

	@ResponseBody
	@RequestMapping("getfirstlev")
	public String firstlev() {

		// System.out.println(cateservice.getfirstlev());
		return JSONArray.toJSONString(cateservice.getfirstlev());
	}

	@ResponseBody
	@RequestMapping("getsecondlev")
	public String secondlev(HttpServletRequest request) {
		String firstcode = request.getParameter("datasent");
		return JSONArray.toJSONString(cateservice.getsecondlev(firstcode));
	}

	@ResponseBody
	@RequestMapping("getthirdlev")
	public String thirdlev(HttpServletRequest request) {
		String firCode = request.getParameter("firCode");
		String secCode = request.getParameter("secCode");
		return JSONArray.toJSONString(cateservice.queryCategoryList(firCode, secCode));
	}
	@RequestMapping("data-seraching")
	public String toSearch(){
		return "/data-searching";
	}
	@RequestMapping("data-entrying")
	public String toEntry(){
		return "/data-entrying";
	}
	@RequestMapping("index")
	public String toIndex(){
		return "../index";
	}
}   
     

